package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.AlarmType;
import com.ruoyi.system.domain.AlarmTypeCompany;
import com.ruoyi.system.domain.request.alarmtype.AlarmTypeExistParam;
import com.ruoyi.system.domain.request.alarmtype.AlarmTypeLevelSettingParam;
import com.ruoyi.system.mapper.AlarmTypeMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IAlarmTypeCompanyService;
import com.ruoyi.system.service.IAlarmTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 告警类型Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class AlarmTypeServiceImpl extends ServiceImpl<AlarmTypeMapper, AlarmType> implements IAlarmTypeService {

    @Autowired
    private AlarmTypeMapper alarmTypeMapper;
    @Autowired
    private IAlarmTypeCompanyService alarmTypeCompanyService;

    @Override
    public List<AlarmType> selectList(AlarmType alarmType) {
        if (alarmType.getCompanyId() == null) alarmType.setCompanyId(SecurityUtils.getRootDeptId());
        return alarmTypeMapper.list(alarmType);
    }

    /**
     * 由告警等级获取对应告警类型
     *
     * @param level
     */
    public List<Integer> alarmLevelToAlarmTypeList(Integer level) {
        List<Integer> typeList = new ArrayList<>();
        //如果是管理员则查询全部,否则查询用户的总公司
        List<AlarmType> alarmTypeList = selectList(new AlarmType());
        //若自定义了告警等级，则使用levelSetting的设置，否则使用默认level
        alarmTypeList.forEach(item -> {
            if (item.getLevelSetting() != null) {
                if (level == item.getLevelSetting().intValue()) {
                    typeList.add(item.getType());
                }
            } else {
                if (level == item.getLevel().intValue()) {
                    typeList.add(item.getType());
                }
            }
        });
        return typeList;
    }

    /**
     * 获取用户所属公司的告警类型
     * @return
     */
    @Override
    public Map<Integer, AlarmType> getUserAlarmTypeMap() {
        LoginUser user = SecurityUtils.getLoginUser();
        List<AlarmType> alarmTypeList = selectList(new AlarmType().setCompanyId(user.getDeptId()));
        //将list转换map. value是对象本身,key冲突的解决办法，这里选择第二个key覆盖第一个key。
        return alarmTypeList.stream().collect(Collectors.toMap(AlarmType::getType, Function.identity(), (key1, key2) -> key2));
    }

    /**
     * 告警名称校验
     * @param param
     */
    @Override
    public void checkExistName(AlarmTypeExistParam param){
        QueryWrapper<AlarmType> nameQuery = new QueryWrapper<AlarmType>().eq("name", param.getName());
        if (param.getId() != null) nameQuery.ne("id", param.getId());
        int nameCount = count(nameQuery);
        if (nameCount > 0) throw new ServiceException("该名称已存在！");
        QueryWrapper<AlarmType> typeQuery = new QueryWrapper<AlarmType>().eq("type", param.getType());
        if (param.getId() != null) typeQuery.ne("id", param.getId());
        int typeCount = count(typeQuery);
        if (typeCount > 0) throw new ServiceException("该类型已存在！");
    }

    /**
     * 告警等级设置
     */
    @Transactional
    @Override
    public void levelSetting(AlarmTypeLevelSettingParam param){
        //删除之前的自定义告警等级设置
        LoginUser user = SecurityUtils.getLoginUser();
        Long rootDeptId = SecurityUtils.isAdmin() ? user.getDeptId() : SecurityUtils.getRootDeptId();
        alarmTypeCompanyService.remove(new QueryWrapper<AlarmTypeCompany>()
                .eq("company_id", rootDeptId)
                .in("alarm_type_id", param.getIds()));
        //恢复默认设置，删除记录后直接返回
        if (param.getLevel() == -1) return;
        //批量新增
        List<AlarmTypeCompany> resultList = Arrays.stream(param.ids).map(id -> {
            AlarmTypeCompany alarmTypeCompany = new AlarmTypeCompany()
                    .setLevel(param.getLevel())
                    .setCompanyId(rootDeptId)
                    .setAlarmTypeId(id);
            return alarmTypeCompany;
        }).collect(Collectors.toList());
        alarmTypeCompanyService.saveBatch(resultList);
    }
}
